#!/bin/bash

receipt="$1"

function help {
  echo "usage: compile.sh receipt.sh"
  exit 1
}

[ -z "$receipt" ] && help || source "$receipt"
mkdir -p src
PACKAGE="$NAME-$VERSION"

function download {
  wget -q --show-progress -c "$BASEURL/$PACKAGE.$1" -O "src/$PACKAGE.$1"
}

download "$PKGEXT"

[ ! -z "$GPGEXT" ] && (
  download "$PKGEXT.$GPGEXT"
  pushd src/ >/dev/null
  gpg --verify "$PACKAGE.$PKGEXT.$GPGEXT" || exit 1
  popd >/dev/null
)
[ ! -z "$SHA" ] && (
  pushd src/ >/dev/null
  echo -e "$SHA\t$PACKAGE.$PKGEXT" > "$PACKAGE.$SHAEXT"
  popd >/dev/null
) || (
  download "$SHAEXT"
)

function configureit {
  ./configure --prefix="$PWD/../dist/" $@
}

function makeit {
  make $@ install
}

function any_debian_pkg_not_installed {
  apt-cache policy $@ | grep Installed | cut -d: -f2 | grep none >/dev/null
}

[ ! -z "$DEBIAN_DEPENDS" ] && any_debian_pkg_not_installed $DEBIAN_DEPENDS && (
  echo '(Debian) Uma ou mais dependências não estão instaladas.'
  echo 'Por favor, entre a senha root para instalar as dependências'
  su -c "apt install -y $DEBIAN_DEPENDS"
)

pushd src/ >/dev/null
  $SHAEXT --quiet --check --ignore-missing "$PACKAGE.$SHAEXT" && echo shasum ok || exit 1
  [ ! -d "$PACKAGE" ] && tar xf "$PACKAGE.$PKGEXT"
  pushd "$PACKAGE" >/dev/null
    unset CFLAGS
    [ -z "${CONFIGFLAGS+x}" ] || configureit $CONFIGFLAGS
    [ -z "${MAKEFLAGS+x}" ] || makeit $MAKEFLAGS
  popd >/dev/null
popd >/dev/null